<template>
  <div class="product-content">
    <div class="tree">
      <el-input placeholder="输入关键字进行过滤" v-model="filterText"
        style="position: sticky; top: 0; margin-bottom:20px; z-index: 99">
      </el-input>
      <el-tree class="filter-tree" :data="data" :props="defaultProps" :default-expand-all="false" style="z-index: 88;"
        :filter-node-method="filterNode" ref="tree" @node-click="handleNodeClick" highlight-current
        :expand-on-click-node="false">
      </el-tree>
    </div>
    <div class="table">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

        <el-form-item label="供应商" prop="provide">
          <el-input v-model="queryParams.provide" :disabled="provideShow" placeholder="请输入供应商" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="车型" prop="busModel" v-if="queryParams.busModel !== ''">
          <el-input v-model="queryParams.busModel" placeholder="请输入车型" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="产品编码" prop="provide">
          <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="产品名称" prop="provide">
          <el-input v-model="queryParams.productName" placeholder="输入产品名称,以%前后拼接" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList2"></right-toolbar>
      </el-row>

      <el-table :data="tableData" style="width: 100%" border v-loading="tableLoading" element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading">

        <el-table-column prop="index" label="序号" align="center" width = "50">
        </el-table-column>
        <el-table-column prop="provide" label="供应商" width="100" align="center">
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="150" align="center">
        </el-table-column>
        <el-table-column prop="productCode" label="产品编号" align="center" width="180">
        </el-table-column>
        <el-table-column prop="productGroup" :label="queryParams.productGroup !== '' ? '开票类型' : '产品类型'" align="center">
        </el-table-column>

        <el-table-column prop="productName" label="产品名称" align="center">
        </el-table-column>
        <el-table-column prop="model" label="型号" width="190" align="center">
        </el-table-column>
        <el-table-column prop="specs" label="规格" align="center">
        </el-table-column>
        <el-table-column prop="busModel" label="适配车型" align="center">
        </el-table-column>
        <el-table-column prop="productMoney" label="进价" align="center">
          <template slot-scope="scope">
            <span style="float:right;cursor: pointer;color:blue" @click="moneyClick(scope.row.productCode)"> {{
        scope.row.productMoney ? formatNumber(parseFloat(scope.row.productMoney.startInMoney).toFixed(2)) : ''
      }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productMoney" v-if="this.deptName === '物资公司'" label="售价" align="center">
          <template slot-scope="scope">
            <span style="float:right;cursor: pointer;color:blue" @click="moneyClick(scope.row.productCode)"> {{
        scope.row.productMoney ? formatNumber(parseFloat(scope.row.productMoney.startOutMoney).toFixed(2)) : ''
      }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
          v-if="checkPermi(['system:modify:price'])">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">调价</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" layout="total, sizes, prev, pager, next, jumper" :total="total"
        :page.sync="queryParams.pageNum" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :limit.sync="queryParams.pageSize" @pagination="getList2" style="margin-bottom:20px" />
    </div>
    <el-dialog :visible.sync="dialogVisible" class="DialogImg" width="1200px" :title="'产品编号:' + productCode">
      <el-table :data="moneyList1" style="width: 100%" border>

        <el-table-column prop="index" label="序号" align="center">
        </el-table-column>
        <el-table-column prop="startInMoney" label="开始进价" align="center">
          <template slot-scope="scope">
            <span style="float:right"> {{ scope.row.startInMoney ?
        formatNumber(parseFloat(scope.row.startInMoney).toFixed(2)) : ""
              }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="endInMoney" label="结束进价" align="center">
          <template slot-scope="scope">
            <span style="float:right;"> {{
        scope.row.endInMoney ? formatNumber(parseFloat(scope.row.endInMoney).toFixed(2)) : ""
      }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="startOutMoney" label="开始售价" width="190" align="center" v-if="this.deptName === '物资公司'">
          <template slot-scope="scope">
            <span style="float:right"> {{
        scope.row.startOutMoney ? formatNumber(parseFloat(scope.row.startOutMoney).toFixed(2)) : ""
      }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endOutMoney" label="结束售价" align="center" v-if="this.deptName === '物资公司'">
          <template slot-scope="scope">
            <span style="float:right"> {{
        scope.row.endOutMoney ? formatNumber(parseFloat(scope.row.endOutMoney).toFixed(2)) : ""
      }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" align="center" width="180">
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" align="center" width="180">
        </el-table-column>
      </el-table>
      <pagination v-show="total1 > 0" layout="total, sizes, prev, pager, next, jumper" :total="total1"
        :page.sync="queryForm.pageNum" @size-change="handleSizeChange1" @current-change="handleCurrentChange1"
        :limit.sync="queryForm.pageSize" @pagination="getMoneyList" style="margin-bottom:20px" />
    </el-dialog>


    <el-dialog title="产品调价" :visible.sync="open" width="500px" append-to-body :show-close="false"
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="产品编号" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入产品编号" :disabled="true" />
        </el-form-item>
        <el-form-item label="开始进价" prop="startInMoney">
          <el-input v-model="form.startInMoney" placeholder="请输入进价" :disabled="true" />
        </el-form-item>
        <el-form-item label="修改进价" prop="endInMoney">
          <el-input v-model="form.endInMoney" @blur="handleBlur" placeholder="请修改进价" />
        </el-form-item>
        <el-form-item label="开始售价" prop="startOutMoney" v-if="this.deptName === '物资公司'">
          <el-input v-model="form.startOutMoney" placeholder="请输入售价" :disabled="true" />
        </el-form-item>
        <el-form-item label="修改售价" prop="endOutMoney" v-if="this.deptName === '物资公司'">
          <el-input v-model="form.endOutMoney" @blur="handleBlur" placeholder="请修改售价" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGroupTree, productList, moneyList, productMoney, productMoneyAdd } from '@/api/system/productClassification';
import { checkPermi } from "@/utils/permission"; // 权限判断函数

export default {
  data() {
    return {
      filterText: '',
      data: [],
      defaultProps: {
        children: 'childList',
        label: 'name'
      },
      tableData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        provide: "",
        productCode: "",
        productName: "",
        productGroup: "",
        busModel: ""
      },
      queryForm: {
        pageNum: 1,
        pageSize: 10,
      },
      moneyList1: [],
      total: 0,
      total1: 0,
      showSearch: true,
      dialogVisible: false,
      productCode: "",
      form: {
        id: "",
        startInMoney: "",
        productCode: "",
        endInMoney: "",
        startOutMoney: "",
        endOutMoney: "",
        status: "",
        startTime: "",
        endTime: ""
      },
      rules: {},
      open: false,
      deptName: "",
      provideShow: false,
      tableLoading: false
    }
  },
  watch: {
    filterText(value) {
      this.$refs.tree.filter(value);
    }
  },
  mounted() {
    const User = localStorage.getItem('User');
    this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
    if (this.deptName !== '物资公司') {
      this.queryParams.provide = this.deptName;
      this.provideShow = true;
    } else {
      this.queryParams.provide = "";
      this.provideShow = false;
    }
    this.getList();
    this.getList2();
  },
  methods: {
    checkPermi,
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    getList() {
      getGroupTree().then(rst => {
        this.data = rst.data;
      })
    },
    getList2() {
      this.tableLoading = true;
      productList(this.queryParams).then(rst => {
        this.tableData = rst.rows;
        this.tableData.forEach((item, index) => {
          item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        });
        this.total = rst.total;
      }).finally(() => {
        this.tableLoading = false;
      })
    },
    // 分页
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
    },
    handleSizeChange1(val) {
      this.queryForm.pageSize = val;
    },
    handleCurrentChange1(val) {
      this.queryForm.pageNum = val;
    },
    handleNodeClick(data) {
      if (data.name === '产品' || data.name === '开票类信息' || data.name === '产品分类' || data.name === '九大类') {
        this.queryParams.productGroup = "";
        this.queryParams.productCode = "";
        this.queryParams.busModel = "";
      } else {
        this.queryParams.productCode = "";
        this.queryParams.productGroup = "";
        this.queryParams.busModel = "";


        // 开票类型
        if (data.code === "") {
          this.queryParams.productGroup = data.name;
        }

        // 九大累
        if (data.code !== '') {
          this.queryParams.productCode = data.code;
        }

        // 车型
        if (data.hasOwnProperty('id')) {
          this.queryParams.busModel = data.name;
        }
      }
      this.getList2();
    },


    handleQuery() {
      this.getList2();
    },
    resetQuery() {
      this.defaultExpandedKeys = [];
      this.queryParams.pageSize = 10;
      this.queryParams.pageNum = 1;
      const User = localStorage.getItem('User');
      this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
      if (this.deptName !== '物资公司') {
        this.queryParams.provide = this.deptName;
        this.provideShow = true;
      } else {
        this.queryParams.provide = "";
        this.provideShow = false;
      }
      this.queryParams.productCode = "";
      this.queryParams.productName = "";
      this.queryParams.productGroup = "";
      this.filterText = "";
      this.getList2();
      this.getList();

    },
    // 数字转换
    formatNumber(value) {
      if (value) {
        let [integerPart, decimalPart] = value.toString().split('.');
        let formattedNumber = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + decimalPart.slice(0, 3);
        return formattedNumber;
      }
    },
    //
    moneyClick(productCode) {
      this.productCode = productCode;
      this.dialogVisible = true;
      this.getMoneyList();
    },
    getMoneyList() {
      moneyList(this.productCode, this.queryForm.pageNum, this.queryForm.pageSize).then(rst => {
        this.moneyList1 = rst.rows;
        this.moneyList1.forEach((item, index) => {
          item.index = (this.queryForm.pageNum - 1) * this.queryForm.pageSize + index + 1;
        });
        this.total1 = rst.total;
      })
    },
    formDate() {
      // 获取当前日期
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleUpdate(row) {
      console.log(row, "asdsad")
      this.form.status = '0';
      this.form.id = row.productMoney.id;
      this.form.productCode = row.productCode;
      this.form.startInMoney = row.productMoney.startInMoney;
      this.form.startOutMoney = row.productMoney.startOutMoney;
      this.form.startTime = row.productMoney.startTime;
      // 设置 endTime 属性为当前日期的格式化字符串
      this.form.endTime = this.formDate();
      this.open = true;
    },
    submitForm() {
      console.log(this.form, 'asad')
      const User = localStorage.getItem('User');
      this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
      if (this.deptName !== '物资公司') {
        this.queryParams.provide = this.deptName;
        this.provideShow = true;
        this.form.endOutMoney = this.form.startOutMoney;
      } else {
        this.queryParams.provide = "";
        this.provideShow = false;
      }
      console.log(this.form, 'form');
      productMoney(this.form).then(rst => {
        if (rst.code === 200) {
          this.productMoneyAdd(this.form);
        }
      })
    },
    productMoneyAdd(row) {
      console.log(row, "1234");
      const params = {
        productCode: row.productCode,
        startInMoney: row.endInMoney,
        startOutMoney: row.endOutMoney,
        status: '1',
        startTime: this.form.endTime
      }
      productMoneyAdd(params).then(rst => {
        if (rst.code === 200) {
          this.open = false;
          this.$message.success(rst.msg);
          this.getList2();

        }
      })
      this.reset();
    },
    // 表单重置
    reset() {
      this.form.status = '';
      this.form.id = '';
      this.form.productCode = '';
      this.form.startInMoney = '';
      this.form.startOutMoney = '';
      this.form.startTime = '';
      this.form.endInMoney = '',
        this.form.endOutMoney = "",
        this.form.endTime = ""
      this.resetForm("form");
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    handleBlur() {
      // 检查输入值是否为数字
      const isNumeric = /^\d+(\.\d+)?$/.test(this.form.endInMoney) || this.form.endInMoney === '';
      const isNumeric1 = /^\d+(\.\d+)?$/.test(this.form.endOutMoney) || this.form.endOutMoney === '';
      if (!isNumeric1) {
        this.$message.error('请输入数字');
        this.form.endOutMoney = ''
      }
      if (!isNumeric) {
        this.$message.error('请输入数字');
        this.form.endInMoney = ''
      }
    }

  }

}
</script>

<style lang="scss" scoped>
.product-content {
  display: flex;
  margin-top: 30px;
  margin: 50px 20px 0 20px;

  .tree {
    // width: 20%;
    width: 300px;
    max-height: 700px;
    overflow: hidden;
    overflow-y: auto;
    margin-right: 15px;
    padding-right: 15px;
  }

  .table {
    width: 78%;

  }
}
</style>
